<!doctype html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../assert_selection.js"></script>
<script src="spellcheck_test.js"></script>

<script>
function runIdleTimeSpellCheckerIfNeeded(document) {
  if (!window.internals)
    return;
  internals.runIdleTimeSpellChecker(document);
}

function pasteToAllChildren(text, container) {
  const document = container.ownerDocument;
  const selection = document.getSelection();
  selection.setClipboardData(text);
  container.childNodes.forEach(child => {
    if (child.nodeName === 'DIV') {
      selection.selectAllChildren(child);
    } else {
      child.value = '';
      child.focus();
    }
    document.execCommand('paste');
  });
}

spellcheck_test(
  [
    '<div id="container">',
      '<textarea></textarea>',
      '<div contenteditable></div>',
      '<input>',
    '</div>'
  ].join(''),
  document => {
    const container = document.getElementById('container');
    pasteToAllChildren('foo bar', container);
    runIdleTimeSpellCheckerIfNeeded(document);
    pasteToAllChildren('zz apple orange', container);
  },
  [
    '<div id="container">',
      '<textarea>#zz# apple orange</textarea>',
      '<div contenteditable>#zz# apple orange</div>',
      '<input value="#zz# apple orange">',
    '</div>'
  ].join(''),
  'Spellchecker handles multiple requests.');

// Regression test for crbug.com/681760
spellcheck_test(
  [
    '<textarea id="textarea1"></textarea>',
    '<textarea id="textarea2"></textarea>'
  ].join(''),
  document => {
    const textarea1 = document.getElementById('textarea1');
    const textarea2 = document.getElementById('textarea2');
    textarea1.focus();
    document.execCommand('insertText', false, 'foo. ');
    runIdleTimeSpellCheckerIfNeeded(document);
    textarea2.focus();
    document.execCommand('insertText', false, 'baz. ');
    runIdleTimeSpellCheckerIfNeeded(document);
    textarea1.focus();
    document.execCommand('insertText', false, 'zz. ');
  },
  [
    '<textarea id="textarea1">#foo#. #zz#. </textarea>',
    '<textarea id="textarea2">#baz#. </textarea>'
  ].join(''),
  'Spellchecker invokes requests in sequence order.');
</script>
